package com.jumi.microservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.common.constant.ImageResizeEnum;
import com.jumi.microservice.common.utils.ImageResizeUtil;
import com.jumi.microservice.common.utils.ObjectUtils;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.NumberConstant;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.mapper.*;
import com.jumi.microservice.service.GoodsDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品详情管理service组件
 *
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsDetailServiceImpl implements GoodsDetailService {

    /**
     * 商品管理mapper组件
     */
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 商品图片管理mapper组件
     */
    @Autowired
    private GoodsPictureMapper goodsPictureMapper;

    /**
     * 商品sku管理mapper组件
     */
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;

    /**
     * 商品sku属性值管理mapper组件
     */
    @Autowired
    private GoodsSkuPropertyValueMapper goodsSkuPropertyValueMapper;

    /**
     * 标签管理Mapper组件
     */
    @Autowired
    private LabelMapper labelMapper;

    /**
     * 素材管理Mapper组件
     */
    @Autowired
    private SourceMaterialMapper sourceMaterialMapper;

    /**
     * 品牌管理Mapper组件
     */
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 根据商品id查询商品详情
     *
     * @param goodsId 商品id
     * @return 商品详情
     */
    @Override
    public GoodsDetailDTO getDetailByGoodsId(Long goodsId) {
        GoodsDetailDTO goodsDetail = new GoodsDetailDTO();

        GoodsDO goods = goodsMapper.selectById(goodsId);
        ExceptionEnum.FAIL_NULL.doThrowIf(goods == null);

        if(goods.getIsDel().equals(NumberConstant.NUMBER_ONE.intValue())){
            return goodsDetail;
        }

        goodsDetail.setGoodsId(goodsId);
        goodsDetail.setGoodsName(goods.getGoodsName());
        goodsDetail.setGoodsType(goods.getGoodsType());
        goodsDetail.setGoodsDescription(goods.getGoodsDescription());
        goodsDetail.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
        goodsDetail.setGoodsPrice(goods.getGoodsPrice());
        goodsDetail.setGoodsMarketprice(goods.getGoodsMarketprice());
        goodsDetail.setGoodsBody(goods.getGoodsBody());
        goodsDetail.setGoodsState(goods.getGoodsState());
        goodsDetail.setIsImport(goods.getIsImport());
        goodsDetail.setVideoUrl(goods.getVideoUrl());

        LambdaQueryWrapper<GoodsPictureDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GoodsPictureDO::getGoodsId, goodsId);
        List<GoodsPictureDO> goodsPictures = goodsPictureMapper.selectList(wrapper);
        for (GoodsPictureDO goodsPictureDO : goodsPictures) {
            goodsPictureDO.setGoodsImage(ImageResizeUtil.imageResize(goodsPictureDO.getGoodsImage(), ImageResizeEnum.DETAIL_BANNER));
        }
        goodsDetail.setGoodsImage(convertGoodsPictureDoList2DtoList(goodsPictures));

        LambdaQueryWrapper<GoodsSkuDO> goodsSkuWrapper = Wrappers.lambdaQuery();
        goodsSkuWrapper.eq(GoodsSkuDO::getGoodsId, goodsId);
        goodsSkuWrapper.eq(GoodsSkuDO::getIsDel, NumberConstant.NUMBER_ZERO.intValue());
        List<GoodsSkuDO> goodsSkus = goodsSkuMapper.selectList(goodsSkuWrapper);

        List<SkuDetailDTO> goodsSkuDtos = new ArrayList<>();
       // List<Long> goodsSkuIds = new ArrayList<>();
        for (GoodsSkuDO goodsSkuDo : goodsSkus) {
            SkuDetailDTO skuDetailDto = new SkuDetailDTO();
            skuDetailDto.setSkuId(goodsSkuDo.getId());
            skuDetailDto.setSkuName(goodsSkuDo.getGoodsName());
            skuDetailDto.setGoodsPrice(goodsSkuDo.getGoodsPrice());
            skuDetailDto.setGoodsMarketprice(goodsSkuDo.getGoodsMarketprice());
            skuDetailDto.setPlatinumPrice(goodsSkuDo.getPlatinumPrice());
            skuDetailDto.setDiamondsPrice(goodsSkuDo.getDiamondsPrice());
            skuDetailDto.setKingPrice(goodsSkuDo.getKingPrice());
            skuDetailDto.setSpecName(goodsSkuDo.getSpecName());
            skuDetailDto.setGoodsPropertyImage(ImageResizeUtil.imageResize(goodsSkuDo.getGoodsPropertyImage(), ImageResizeEnum.LARGE));
            skuDetailDto.setVirtualNum(goodsSkuDo.getVirtualNum());

            LambdaQueryWrapper<GoodsSkuPropertyValueDO> goodsSkuPropertyValueWrapper = Wrappers.lambdaQuery();
            goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getGoodsSkuId, goodsSkuDo.getId());

            List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues =
                    goodsSkuPropertyValueMapper.selectList(goodsSkuPropertyValueWrapper);
            skuDetailDto.setGoodsSkuPropertyValue(convertGoodsSkuPropertyValueList2DtoList(goodsSkuPropertyValues));
            goodsSkuDtos.add(skuDetailDto);
            //goodsSkuIds.add(goodsSkuDo.getId());

        }
        goodsDetail.setGoodsSkus(goodsSkuDtos);
        //goodsDetail.setGoodsSkuIds(goodsSkuIds);

        List<String> labels = new ArrayList<>();
        if (StringUtils.isNotBlank(goods.getGoodsLabel())) {
            String[] goodsLabelIds = goods.getGoodsLabel().split(",");
            LambdaQueryWrapper<LabelDO> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.eq(LabelDO::getIsDel, StatusEnum.STATUS_NO.getCode());
            lambdaQuery.eq(LabelDO::getStatus, StatusEnum.STATUS_YES.getCode());
            lambdaQuery.in(LabelDO::getId, goodsLabelIds);
            List<LabelDO> labelList = labelMapper.selectList(lambdaQuery);
            for (LabelDO label : labelList) {
                labels.add(label.getLabelName());
            }
        }
        goodsDetail.setLabel(labels);

        //查询商品素材
        List<Integer> moduleTypeList = new ArrayList<>();
        moduleTypeList.add(NumberConstant.NUMBER_ZERO.intValue());
        moduleTypeList.add(NumberConstant.NUMBER_ONE.intValue());

        LambdaQueryWrapper<SourceMaterialDO> sourceMaterialWrapper = Wrappers.lambdaQuery();
        sourceMaterialWrapper.eq(SourceMaterialDO::getSpuGoodsId, goodsId);
        sourceMaterialWrapper.eq(SourceMaterialDO::getStatus, NumberConstant.NUMBER_ONE.intValue());
        sourceMaterialWrapper.in(SourceMaterialDO::getModuleType, moduleTypeList);
        sourceMaterialWrapper.orderByDesc(SourceMaterialDO::getCreateTime);
        List<SourceMaterialDO> sourceMaterials = sourceMaterialMapper.selectList(sourceMaterialWrapper);

        goodsDetail.setSurceMaterialCount(sourceMaterials.size());
        if (sourceMaterials.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            SourceMaterialDO sourceMaterialDO = sourceMaterials.get(NumberConstant.NUMBER_ZERO.intValue());
            SourceMaterialDetailDTO sourceMaterialDetailDto = convertSourceMaterial2Dto(sourceMaterialDO);

            List<String> sourceMaterialImageList = Arrays.asList(sourceMaterialDetailDto.getSourceMaterialImage().split("\\|"));
            sourceMaterialImageList = sourceMaterialImageList.stream().map(image -> ImageResizeUtil.imageResize(image, ImageResizeEnum.LIST)).collect(Collectors.toList());
            sourceMaterialDetailDto.setSourceMaterialImage(String.join("|", sourceMaterialImageList));
            goodsDetail.setSourceMaterial(sourceMaterialDetailDto);
        }
        goodsDetail.setVirtualNum(goodsSkuMapper.countVirtualNumBySpuId(goodsId));
        return goodsDetail;
    }

    /**
     * 将商品素材DO对象转换为DTO对象
     *
     * @param sourceMaterial 商品素材DO
     * @return SourceMaterialDTO 商品素材DTO对象
     */
    private SourceMaterialDetailDTO convertSourceMaterial2Dto(SourceMaterialDO sourceMaterial) {
        SourceMaterialDetailDTO targetSourceMaterial = null;
        try {
            targetSourceMaterial = sourceMaterial.clone(SourceMaterialDetailDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return targetSourceMaterial;
    }


    /**
     * 根据商品sku id查询商品详情
     *
     * @param goodsSkuId 商品 sku id
     * @return 商品详情
     */
    @Override
    public GoodsDetailDTO getDetailByGoodsSkuId(Long goodsSkuId) {
        GoodsDetailDTO goodsDetail = new GoodsDetailDTO();
        GoodsSkuDO goodsSkuDO = goodsSkuMapper.selectById(goodsSkuId);
        ExceptionEnum.FAIL_NULL.doThrowIf(goodsSkuDO == null);

        GoodsSkuDTO goodsSkuDTO = convertGoodsSkuDo2Dto(goodsSkuDO);

        GoodsDO goods = goodsMapper.selectById(goodsSkuDO.getGoodsId());
        ExceptionEnum.FAIL_NULL.doThrowIf(goods == null);

        if(goods.getIsDel().equals(NumberConstant.NUMBER_ONE.intValue())){
            return goodsDetail;
        }

        GoodsDTO goodsDto = convertGoodsDo2Dto(goods);
        goodsDetail.setGoodsId(goodsSkuDO.getGoodsId());
        goodsDetail.setGoodsName(goodsDto.getGoodsName());
        goodsDetail.setGoodsType(goodsDto.getGoodsType());
        goodsDetail.setGoodsDescription(goodsDto.getGoodsDescription());
        goodsDetail.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
        goodsDetail.setGoodsPrice(goodsSkuDTO.getGoodsPrice());
        goodsDetail.setGoodsMarketprice(goodsSkuDTO.getGoodsMarketprice());
        goodsDetail.setGoodsBody(goodsDto.getGoodsBody());
        goodsDetail.setGoodsState(goodsDto.getGoodsState());
        goodsDetail.setIsImport(goods.getIsImport());
        goodsDetail.setVideoUrl(goods.getVideoUrl());

        LambdaQueryWrapper<GoodsPictureDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GoodsPictureDO::getGoodsId, goodsSkuDO.getGoodsId());
        List<GoodsPictureDO> goodsPictures = goodsPictureMapper.selectList(wrapper);
        for (GoodsPictureDO goodsPictureDO : goodsPictures) {
            goodsPictureDO.setGoodsImage(ImageResizeUtil.imageResize(goodsPictureDO.getGoodsImage(), ImageResizeEnum.DETAIL_BANNER));
        }
        goodsDetail.setGoodsImage(convertGoodsPictureDoList2DtoList(goodsPictures));

        LambdaQueryWrapper<GoodsSkuDO> goodsSkuWrapper = Wrappers.lambdaQuery();
        goodsSkuWrapper.eq(GoodsSkuDO::getGoodsId, goodsSkuDO.getGoodsId());
        goodsSkuWrapper.eq(GoodsSkuDO::getIsDel, NumberConstant.NUMBER_ZERO.intValue());
        List<GoodsSkuDO> goodsSkus = goodsSkuMapper.selectList(goodsSkuWrapper);

        List<SkuDetailDTO> goodsSkuDtos = new ArrayList<>();
        for (GoodsSkuDO goodsSkuDo : goodsSkus) {
            SkuDetailDTO skuDetailDto = new SkuDetailDTO();
            skuDetailDto.setSkuId(goodsSkuDo.getId());
            skuDetailDto.setSkuName(goodsSkuDo.getGoodsName());
            skuDetailDto.setGoodsPrice(goodsSkuDo.getGoodsPrice());
            skuDetailDto.setGoodsMarketprice(goodsSkuDo.getGoodsMarketprice());
            skuDetailDto.setPlatinumPrice(goodsSkuDo.getPlatinumPrice());
            skuDetailDto.setDiamondsPrice(goodsSkuDo.getDiamondsPrice());
            skuDetailDto.setKingPrice(goodsSkuDo.getKingPrice());
            skuDetailDto.setSpecName(goodsSkuDo.getSpecName());
            skuDetailDto.setGoodsPropertyImage(goodsSkuDo.getGoodsPropertyImage());
            skuDetailDto.setVirtualNum(goodsSkuDo.getVirtualNum());

            LambdaQueryWrapper<GoodsSkuPropertyValueDO> goodsSkuPropertyValueWrapper = Wrappers.lambdaQuery();
            goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getGoodsSkuId, goodsSkuDo.getId());

            List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues =
                    goodsSkuPropertyValueMapper.selectList(goodsSkuPropertyValueWrapper);
            skuDetailDto.setGoodsSkuPropertyValue(convertGoodsSkuPropertyValueList2DtoList(goodsSkuPropertyValues));
            goodsSkuDtos.add(skuDetailDto);
        }
        goodsDetail.setGoodsSkus(goodsSkuDtos);

        List<String> labels = new ArrayList<>();
        if (StringUtils.isNotBlank(goods.getGoodsLabel())) {
            String[] goodsLabelIds = goods.getGoodsLabel().split(",");
            LambdaQueryWrapper<LabelDO> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.eq(LabelDO::getIsDel, StatusEnum.STATUS_NO.getCode());
            lambdaQuery.eq(LabelDO::getStatus, StatusEnum.STATUS_YES.getCode());
            lambdaQuery.in(LabelDO::getId, goodsLabelIds);
            List<LabelDO> labelList = labelMapper.selectList(lambdaQuery);
            for (LabelDO label : labelList) {
                labels.add(label.getLabelName());
            }
        }
        goodsDetail.setLabel(labels);

        //查询商品素材
        List<Integer> moduleTypeList = new ArrayList<>();
        moduleTypeList.add(NumberConstant.NUMBER_ZERO.intValue());
        moduleTypeList.add(NumberConstant.NUMBER_ONE.intValue());

        LambdaQueryWrapper<SourceMaterialDO> sourceMaterialWrapper = Wrappers.lambdaQuery();
        sourceMaterialWrapper.eq(SourceMaterialDO::getSpuGoodsId, goods.getId());
        sourceMaterialWrapper.eq(SourceMaterialDO::getStatus, NumberConstant.NUMBER_ONE.intValue());
        sourceMaterialWrapper.in(SourceMaterialDO::getModuleType, moduleTypeList);
        sourceMaterialWrapper.orderByDesc(SourceMaterialDO::getCreateTime);
        List<SourceMaterialDO> sourceMaterials = sourceMaterialMapper.selectList(sourceMaterialWrapper);

        goodsDetail.setSurceMaterialCount(sourceMaterials.size());
        if (sourceMaterials.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            SourceMaterialDO sourceMaterialDO = sourceMaterials.get(NumberConstant.NUMBER_ZERO.intValue());
            SourceMaterialDetailDTO sourceMaterialDetailDto = convertSourceMaterial2Dto(sourceMaterialDO);

            List<String> sourceMaterialImageList = Arrays.asList(sourceMaterialDetailDto.getSourceMaterialImage().split("\\|"));
            sourceMaterialImageList = sourceMaterialImageList.stream().map(image -> ImageResizeUtil.imageResize(image, ImageResizeEnum.LIST)).collect(Collectors.toList());
            sourceMaterialDetailDto.setSourceMaterialImage(String.join("|", sourceMaterialImageList));
            goodsDetail.setSourceMaterial(sourceMaterialDetailDto);
        }
        return goodsDetail;
    }

    /**
     * 将商品DO对象转换为DTO对象
     *
     * @param goods 商品spu DO
     * @return GoodsDTO 商品spu DTO
     */
    private GoodsDTO convertGoodsDo2Dto(GoodsDO goods) {
        GoodsDTO goodsDto = null;
        try {
            goodsDto = goods.clone(GoodsDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsDto;
    }

    /**
     * 将商品SKU DO对象转换为DTO对象
     *
     * @param goodsSku 商品sku DO
     * @return GoodsDTO 商品sku DTO
     */
    private GoodsSkuDTO convertGoodsSkuDo2Dto(GoodsSkuDO goodsSku) {
        GoodsSkuDTO goodsSkuDto = null;
        try {
            goodsSkuDto = goodsSku.clone(GoodsSkuDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsSkuDto;
    }


    /**
     * 将商品图片DO对象集合转换为DTO对象集合
     *
     * @param goodsPictures 商品图片DTO集合
     * @return List<GoodsPictureDTO> 商品图片DTO对象集合
     */
    private List<GoodsPictureDetailDTO> convertGoodsPictureDoList2DtoList(List<GoodsPictureDO> goodsPictures) {
        List<GoodsPictureDetailDTO> goodsPictureDtos = null;
        try {
            goodsPictureDtos = ObjectUtils.convertList(goodsPictures, GoodsPictureDetailDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsPictureDtos;
    }

    /**
     * 将商品sku DO对象集合转换为DTO对象集合
     *
     * @param goodsSkus 商品sku DO集合
     * @return List<GoodsSkuDTO> 商品sku DTO对象集合
     */
    private List<GoodsSkuDTO> convertGoodsSkuList2DtoList(List<GoodsSkuDO> goodsSkus) {
        List<GoodsSkuDTO> goodsSkuDtos = null;
        try {
            goodsSkuDtos = ObjectUtils.convertList(goodsSkus, GoodsSkuDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsSkuDtos;
    }

    /**
     * 将商品sku属性 DO对象集合转换为VO对象集合
     *
     * @param goodsSkuPropertyValues 商品sku 属性DO集合
     * @return List<GoodsSkuPropertyValueDTO> 商品sku属性 DTO对象集合
     */
    private List<GoodsSkuPropertyValueDetailDTO> convertGoodsSkuPropertyValueList2DtoList(
            List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues) {
        List<GoodsSkuPropertyValueDetailDTO> goodsSkuPropertyValueDtos = null;
        try {
            goodsSkuPropertyValueDtos = ObjectUtils.convertList(goodsSkuPropertyValues,
                    GoodsSkuPropertyValueDetailDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsSkuPropertyValueDtos;
    }

    /**
     * 将标签DO对象转换为DTO对象
     *
     * @param label 标签DO
     * @return LabelDTO 标签DTO
     */
    private LabelDTO convertLabelDo2Dto(LabelDO label) {
        LabelDTO labelDto = null;
        try {
            labelDto = label.clone(LabelDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return labelDto;
    }

    /**
     * 将商品素材DO对象集合转换为DTO对象集合
     *
     * @param sourceMaterials 商品素材DO集合
     * @return List<SourceMaterialDTO> 商品素材DTO对象集合
     */
    private List<SourceMaterialDetailDTO> convertSourceMaterialList2DtoList(List<SourceMaterialDO> sourceMaterials) {
        List<SourceMaterialDetailDTO> targetSourceMaterial = null;
        try {
            targetSourceMaterial = ObjectUtils.convertList(sourceMaterials, SourceMaterialDetailDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return targetSourceMaterial;
    }
}
